import Beans from "../../utils/Beans";
import {SimpleDateFormat} from "../../utils/SimpleDateFormat";
import Toast from "../toast/Toast";
import {ChatsStore} from "../../model/store/ChatsContentStore";

var sdk = require('../../utils/echatim-sdk.js');
var EChatIMApis = sdk.apis;
let app = getApp();
let globalStore = app.globalData.globalStore;

const SETDATA_SCROLL_TO_BOTTOM = {
  scrollTop: 100000,
  scrollWithAnimation: true,
};

Component({
  properties: {
    envId: String
  },

  data: {
    chats: [],
    textInputValue: '',
    scrollTop: 0,
  },

  methods: {
    sendMessage(type, jsonBody) {
      const way = (globalStore.chatsContent.select==='friend' || globalStore.chatsContent.select==='session') ? 'P2P' : 'P2R';
      if (way === 'P2P' || way === 'P2R') {
        const form = {}; // MessageSendForm
        form.fromUser = globalStore.userInfo.auid;
        form.toTarget = way === 'P2P' ? globalStore.chatsContent.friendInfo.auid : globalStore.chatsContent.roomInfo.rid + '';
        form.way = way;
        form.type = type;
        form.body = jsonBody;
        EChatIMApis.sendMessage.call(form).then((resp) => {
          // 加入刚刚发的信息到聊天窗口
          const chat = new ChatsStore();
          chat.toMe = 0;
          chat.type = type;
          chat.way = way;
          chat.body = jsonBody;
          chat.createTime = SimpleDateFormat.format(new Date(), 'yyyy-MM-dd hh:mm:ss');
          globalStore.chatsContent.chats.push(chat);
          // notify update
          globalStore.notifyChatUpdate();
          Toast.show("发送成功");
          // globalStore.scrollMessageContainerToBottom();
        }).catch((e) => {
          globalStore.showApiErrorToast(e);
        })
      }
    },

    onScrollToUpper() {

    },

    scrollToBottom(force) {
      if (force) {
        console.log('force scroll to bottom')
        this.setData(SETDATA_SCROLL_TO_BOTTOM)
        return
      }

      this.createSelectorQuery().select('.body').boundingClientRect(bodyRect => {
        this.createSelectorQuery().select(`.body`).scrollOffset(scroll => {
          if (scroll.scrollTop + bodyRect.height * 3 > scroll.scrollHeight) {
            console.log('should scroll to bottom')
            this.setData(SETDATA_SCROLL_TO_BOTTOM)
          }
        }).exec()
      }).exec()
    },

    onConfirmSendText(e) {
      const content = e.detail.value;
      if (!e.detail.value) {
        console.log('请输入内容');
        return
      }
      this.sendMessage('TEXT',{
        body:content
      });
    },

    // 上传文件
    uploadFile(filePath, fileSize) {
      const fileId = this.fileClient.upload(filePath);// 上传文件
      if(fileId){
        this.fileSizeMap[fileId] = parseFloat(fileSize/1024).toFixed(2); // 保存文件大小(KB)
      }
    },

    // 选择相册, 相机
    onChooseImage(e) {
      const self = this;
      wx.chooseImage({
        count: 1,
        sourceType: ['album', 'camera'],
        success: (res) => {
          console.log(res);
          const fileTempPath = res.tempFilePaths[0];
          const fileSize = res.tempFiles[0].size;
          self.uploadFile(fileTempPath, fileSize);
        },
      })
    },
  },


  ready() {
    globalStore.addChatListener((chats)=>{
      this.setData({
        chats:chats.map((v)=>{
          const item = Beans.to(v);
          item.createTimeStr = SimpleDateFormat.formatDateStr(item.createTime,'MM-dd hh:mm');
          return item;
        })
      }, function () {
          // 清空输入框
          this.setData({
            textInputValue:'',
          });
          // 列表滚动到底部
          this.scrollToBottom(true);
      });
    });

    // 获取自己跟 好友/群 的聊天记录
    const historyListForm = {};
    historyListForm.fromUser = globalStore.userInfo.auid;
    historyListForm.toTarget = globalStore.isSelectPersonTag() ? globalStore.chatsContent.friendInfo.auid : globalStore.chatsContent.roomInfo.rid + '';
    historyListForm.way =  globalStore.isSelectPersonTag() ? 'P2P' : 'P2R';
    historyListForm.startTimestamp = 0;
    historyListForm.endTimestamp = new Date().getTime();
    historyListForm.limit = 12;

    EChatIMApis.historyListMessage.call(historyListForm).then((resp) => {
      const msgs = resp.data.reverse();
      globalStore.chatsContent.chats = msgs;
      globalStore.notifyChatUpdate();
    }).catch((e) => {
      globalStore.showApiErrorToast(e);
    });

    const self = this;
    // 初始化 E聊SDK文件上传组件
    const uploadConfig = {};
    uploadConfig.maxFileSize = 10240;
    uploadConfig.allowSuffix = [];
    uploadConfig.type = '';
    this.fileClient = sdk.im.newFileClient();
    const listener = {
      beforeUploadCallback: (info) => {
        return info;
      },
      errorCallback: (info, error) => {
        console.error('errorCallback:' + Beans.json(error));
      },
      progressCallback:(info) => {
        // console.info(`file:${info.originFileName} uploaded:${info.uploadPercent}%`);
      },
      uploadedCallback:(info) => {
        console.info("uploaded:" + Beans.json(info));
        self.sendMessage('IMAGE',{
          body:info.url,
          name:info.originFileName,
          size:self.fileSizeMap.hasOwnProperty(info.id) ? self.fileSizeMap[info.id] : 0
        });
      }
    };
    // E聊SDK上传组件初始化
    this.fileClient.init(uploadConfig, listener);
    this.fileSizeMap = {}; // 记录文件id与大小关系
  },

})
